#!/usr/bin/bash
## All credits to GeorgeHJ on github, thank you!
## Requires mpd, mpc, ueberzug, bash, ffmpeg and diffutils


# This should be the root of mpd
musicDir="/home/overlock/Music"

tmpImgDir="/tmp/ncmpcpp-album"

# Default Dimensions
WIDTH=32
HEIGHT=32
X=0
Y=0


mkdir -p "$tmpImgDir"

mpdRunCheck() {
    while true; do
        mpc -q 2>/dev/null && break || sleep 2
    done
}

updArt() {
    oldFilename="$filename"
    getCoverArt
}

getCoverArt() {
    local curFile; local tmpImgFile #; local curDIr

    curFile=$(mpc current -f "%file%")

    [ -n "$curFile" ] && {
        tmpImgFile=$(mktemp -p "$tmpImgDir" --suffix=.png)
        ffmpeg -i "$musicDir/$curFile" "$tmpImgFile" -y

        if ! cmp -s "$filename" "$tmpImgFile"; then
            filename=$tmpImgFile
        fi

        find "$tmpImgDir" -name "tmp.*.png" 2>/dev/null | grep -v "$filename" | xargs -r rm
    }
}

showArt() {
    # shellcheck disable=2154
    { declare -Ap add_commnand=([action]="add" [identifier]="albumArt" [x]="$X" [y]="$Y" [width]="$WIDTH" [height]="$HEIGHT" [path]="$filename")
        checkChanged
    } | ueberzug layer --parser bash
}


checkChanged() {
    while true; do
        mpc idle player update >/dev/null
        updArt

        if ! cmp -s "$oldFilename" "$filename"; then
            oldFilename="$filename" && break
        fi
    done
}

quit() {
    # shellcheck disable=2154
    {
        declare -Ap remove_command=([action]="remove" [identifier]="albumArt")
    } | ueberzug layer --parser bash

    tput cnorm

    find "$tmpImgDir" -name "tmp.*.png" -delete 2>/dev/null

    exit 0
}


# Main

tput civis

trap quit SIGINT

while true; do
    mpdRunCheck
    updArt
    clear
    showArt
done 2>/dev/null
